﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace PalBattleEmulator.Template.Tools
{
    public class XmlTemplateTools
    {
        /// <summary>
        /// 从Xml文件中读取模板数据
        /// </summary>
        /// <param name="path"></param>
        /// <param name="rootName"></param>
        /// <param name="nodeName"></param>
        /// <returns></returns>
        public static List<Dictionary<string, string>> LoadXmlFile(string path, string rootName, string nodeName)
        {
            List<Dictionary<string, string>> objList = new List<Dictionary<string, string>>();

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(path);
            XmlNode root = xmldoc.SelectSingleNode(rootName);
            if (root == null) return null;
            XmlNodeList nodes = root.SelectNodes(nodeName);
            foreach (XmlNode node in nodes)
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                XmlNodeList children = node.ChildNodes;
                foreach (XmlNode child in children)
                {
                    string key = child.Name;
                    string value = child.InnerText;
                    dic.Add(key, value);
                }
                objList.Add(dic);
            }
            return objList;
        }

        public static void GenerateXmlFile(List<Dictionary<string, string>> data, string path, string rootName, string nodeName)
        {
            XmlDocument xmldoc = new XmlDocument();

            //declaration
            XmlDeclaration declare = xmldoc.CreateXmlDeclaration("1.0", "utf-8", "");
            xmldoc.AppendChild(declare);

            //root
            XmlElement root = xmldoc.CreateElement(rootName);
            xmldoc.AppendChild(root);

            for (int i = 0; i < data.Count; i++)
            {
                Dictionary<string, string> dic = data[i];
                XmlElement node = xmldoc.CreateElement(nodeName);
                root.AppendChild(node);
                foreach(string key in dic.Keys)
                {
                    XmlElement child = xmldoc.CreateElement(key);
                    child.InnerText = dic[key];
                    node.AppendChild(child);
                }
            }


            xmldoc.Save(path);
        }
    }
}
